package cn.lastcc.pwdmanage.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import cn.lastcc.pwdmanage.BuildConfig;
import cn.lastcc.pwdmanage.R;
import cn.lastcc.pwdmanage.core.AesUtil;
import cn.lastcc.pwdmanage.core.CustomApp;
import cn.lastcc.pwdmanage.core.SerialUtil;
import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;
import cn.lastcc.pwdmanage.entity.PwdTag;

public class MainActivity extends Activity {

	public static MainActivity instance = null;
    private SerialUtil mSerialUtil = null;

    private final long exitTime = 2000; // 两次按下后退键的间隔时间(毫秒)
    private long lastExitTime = 0; // 第一次点击返回按钮的时间(毫秒)

    // 声明控件
    private Button btnCreatePwd = null;
    private Button btnPwdList = null;
    private Button btnSetUserPwd = null;
    private Button btnImportPwd = null;
    private Button btnExportPwd = null;
    private Button btnAbout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("管理界面");
        instance = this;
        mSerialUtil = SerialUtil.getInstance(this);
        setContentView(R.layout.activity_main);
        // Show the Up button in the action bar.
//        setupActionBar();
        // 根据 id 获得控件
        btnCreatePwd = this.findViewById(R.id.btnCreatePwd_main);
        btnPwdList = this.findViewById(R.id.btnPwdList_main);
        btnSetUserPwd = this.findViewById(R.id.btnSetUserPwd_main);
        btnImportPwd = this.findViewById(R.id.btnImportPwd_main);
        btnExportPwd = this.findViewById(R.id.btnExportPwd_main);
        btnAbout = this.findViewById(R.id.btnAbout_main);

        CustomApp customApp = (CustomApp) MainActivity.this.getApplication();

        // 如果 Info 文件不存在则不允许创建和管理密码
        if (null == getInfo()) {
            btnCreatePwd.setEnabled(false);
            btnPwdList.setEnabled(false);
            btnImportPwd.setEnabled(false);
            btnExportPwd.setEnabled(false);
        } else {
            Intent intent = this.getIntent();
            if (TextUtils.isEmpty(customApp.getUserPwd())) {
                customApp.setUserPwd(intent.getStringExtra(IConstant.LOGIN_PARAM_PWD_LBL));
            }
        }
        this.btnCreatePwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动创建密码窗口(CreatePwdActivity)
                Intent createPwdIntent = new Intent();
                createPwdIntent.setClass(MainActivity.this, CreatePwdActivity.class);
                startActivity(createPwdIntent);
            }
        });
        this.btnSetUserPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动登录密码修改窗口(UserPwdModifyActivity)
                Intent userPwdModifyIntent = new Intent();
                userPwdModifyIntent.setClass(MainActivity.this, UserPwdModifyActivity.class);
                startActivity(userPwdModifyIntent);
            }
        });
        this.btnPwdList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动密码管理窗口(PwdListActivity)
                Intent pwdListIntent = new Intent();
                pwdListIntent.setClass(MainActivity.this, PwdListActivity.class);
                startActivity(pwdListIntent);
            }
        });
        this.btnImportPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        this.btnExportPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                new AlertDialog.Builder(MainActivity.this)
                .setTitle(R.string.str_export_title)
                .setMessage(String.format(v.getResources().getString(R.string.str_export_msg)
                        , IConstant.PWD_EXPORT_PATH))
                .setPositiveButton(R.string.str_globe_Export, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        final EditText txtLoginPwd = new EditText(MainActivity.this);
                        txtLoginPwd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle(R.string.str_export_verify_login)
                                .setView(txtLoginPwd)
                                .setPositiveButton(R.string.str_globe_Export, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        CustomApp customApp = (CustomApp) MainActivity.this.getApplication();
                                        String logonPwd = customApp.getUserPwd();
                                        if (!logonPwd.equals(txtLoginPwd.getText().toString())) {
                                            Toast.makeText(MainActivity.this, R.string.msg_logonActivity_logonFailed, Toast.LENGTH_SHORT).show();
                                            return ;
                                        }
                                        Writer writer = null;
                                        List<PwdTag> list = getInfo().getPwdTagList();
                                        File file = new File(IConstant.PWD_EXPORT_PATH);
                                        try {
                                            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
                                            JSONObject jObj = new JSONObject();
                                            jObj.put("version", IConstant.EXPORT_VERSION);
                                            JSONArray jAry = new JSONArray();
                                            for (PwdTag pwdTag : list) {
                                                JSONObject jPwdTag = new JSONObject();
                                                byte[] salt = pwdTag.getSalt();
                                                String tagName = new String(AesUtil.decrypt(AesUtil.parseHexStr2Byte(pwdTag.getTagName()), logonPwd, salt));
                                                String pwd = new String(AesUtil.decrypt(AesUtil.parseHexStr2Byte(pwdTag.getPwd()), logonPwd, salt));
                                                jPwdTag.put("tagName", tagName);
                                                jPwdTag.put("pwd", pwd);
                                                jAry.put(jPwdTag);
                                            }
                                            jObj.put("pwdList", jAry);
                                            writer.write(jObj.toString());
                                            writer.flush();
                                            Toast.makeText(MainActivity.this, R.string.str_export_success, Toast.LENGTH_LONG).show();
                                        } catch (IOException | JSONException e) {
                                            e.printStackTrace();
                                            Toast.makeText(MainActivity.this
                                                    , String.format(v.getResources().getString(R.string.str_export_failed),e.getMessage())
                                                    , Toast.LENGTH_LONG)
                                                    .show();
                                        } finally {
                                            if (null != writer) {
                                                try {
                                                    writer.close();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }
                                    }
                                })
                                .setNegativeButton(R.string.str_globe_Cancel, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .create().show();
                    }
                })
                .setNegativeButton(R.string.str_globe_Cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
            }
        });
        this.btnAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    new AlertDialog.Builder(MainActivity.this)
                    .setTitle(R.string.str_about_title)
                    .setMessage(String.format(v.getResources().getString(R.string.app_about)
                            , BuildConfig.BUILD_TYPE
                            , v.getContext().getPackageManager().getPackageInfo(v.getContext().getPackageName() , 0).versionName
                            , BuildConfig.releaseTime))
                    .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();
                } catch (NotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(v.getContext(), R.string.msg_about_alertFailed, Toast.LENGTH_SHORT).show();
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(v.getContext(), R.string.msg_about_alertFailed, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private Info getInfo() {
        Info info = null;
        try {
            info = mSerialUtil.getInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 双击后退键退出应用程序
        if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
            if ((System.currentTimeMillis() - this.lastExitTime) > this.exitTime) {
                Toast.makeText(this, R.string.msg_mainActivity_exitPrompt, Toast.LENGTH_SHORT).show();
                this.lastExitTime = System.currentTimeMillis();
            } else {
                // 退出应用程序
                this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
}
